class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        int maxLength = 0;
        
        function<int(TreeNode*)> dfs = [&](TreeNode* node) -> int {
            if (!node) return 0;
            
            int leftLength = dfs(node->left);
            int rightLength = dfs(node->right);
            
            int extendLeft = 0;
            if (node->left && node->left->val == node->val) {
                extendLeft = leftLength + 1;
            }
            
            int extendRight = 0;
            if (node->right && node->right->val == node->val) {
                extendRight = rightLength + 1;
            }
            
            maxLength = max(maxLength, extendLeft + extendRight);
            
            return max(extendLeft, extendRight);
        };
        
        dfs(root);
        return maxLength;
    }
};
